package com.itwxz.forum.service;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.itwxz.common.constant.CacheConstants;
import com.itwxz.common.constant.UserConstants;
import com.itwxz.common.core.redis.RedisCache;
import com.itwxz.common.exception.user.CaptchaExpireException;
import com.itwxz.common.utils.StringUtils;
import com.itwxz.forum.domain.dto.RegisterForumDto;
import com.itwxz.forum.domain.po.ForumUser;
import com.itwxz.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ForumRegisterService {
    @Autowired
    private ForumUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 注册
     */
    public SaResult register(RegisterForumDto registerDto) {
        String email = registerDto.getEmail();
        String password = registerDto.getPassword();

        if (StringUtils.isEmpty(email))
            return SaResult.error("邮箱不能为空");

        if (StringUtils.isEmpty(password))
            return SaResult.error("用户密码不能为空");

        if (email.length() < UserConstants.USERNAME_MIN_LENGTH
                || email.length() > UserConstants.USERNAME_MAX_LENGTH)
            return SaResult.error("邮箱长度必须在2到45个字符之间");

        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
            return SaResult.error("密码长度必须在5到20个字符之间");


        // 验证码校验（如启用）
        if (configService.selectCaptchaEnabled()) {
            validateEmail(registerDto.getCode(), registerDto.getUuid());
        }

        // 检查邮箱是否已注册
        ForumUser forumUser = new ForumUser();
        forumUser.setUserName(email);
        forumUser.setEmail(email);
        if (!userService.checkUserUnique(forumUser))
            return SaResult.error("保存用户'" + email + "'失败，注册账号已存在");


        // 构建新用户
        forumUser.setNickName("用户" + RandomUtil.randomString(6));
        forumUser.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        forumUser.setPhoneNumber(registerDto.getPhoneNumber());

        boolean saved = userService.save(forumUser);
        if (!saved) return SaResult.error("注册失败，请联系系统管理员");


        return SaResult.ok("注册成功");
    }

    /**
     * 校验邮箱验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateEmail(String code, String uuid) {
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + StringUtils.nvl(uuid, "");
        String email = redisCache.getCacheObject(verifyKey);

        if (email == null) throw new CaptchaExpireException();
        if (!code.equalsIgnoreCase(email)) throw new CaptchaExpireException();

        redisCache.deleteObject(verifyKey);
    }
}
